
import * as cheerio from 'react-native-cheerio';
import { ISearchResult } from "../def";
import { SupportVideoType, VideoIntroduceInfo, VideoDetailInfo, VideoItem, PlaySource, Episode } from "../icommon/index";

async function search<T extends SupportVideoType>(query: string, page: number, type: T): Promise<ISearchResult<T>> {
    const movies: VideoItem[] = [];
    let url = "https://www.iysdq.com/vodtype/1.html";
    switch (type) {
        case "movies":
            url = `https://www.iysdq.com/vodtype/1-${page}.html`;
            break;
        case "tv":
            url = `https://www.iysdq.com/vodtype/2-${page}.html`;
            break;
        case "cartoon":
            url = `https://www.iysdq.com/vodtype/4-${page}.html`;
            break;
        case "all":
            url = `https://www.iysdq.com/vodsearch/${query}----------${page}---.html`
            break;
    }
    const res = await fetch(url, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    $('.public-list-box.public-pic-b').each((index: number, element: any) => {
        const linkElement = $(element).find('a.public-list-exp');
        const titleElement = $(element).find('.time-title'); // 使用更精确的选择器

        if (linkElement.length > 0 && titleElement.length > 0) {
            const detailUrl = linkElement.attr('href') || '';
            const cover = linkElement.find('img').attr('data-src') || '';
            const title = titleElement.text().trim();

            // 修复影片ID提取逻辑，使用更精确的正则表达式匹配/voddetail/138547.html格式的URL
            const idMatch = detailUrl.match(/\/voddetail\/([0-9]+)\.html/);
            const id = idMatch ? idMatch[1] : '';

            // 验证必要字段是否完整
            if (id && title && cover && detailUrl) {
                movies.push({
                    id,
                    title,
                    img: cover,
                    detailUrl,
                });
            }
        }
    });
    return {
        data: movies,
        isEnd: movies.length <= 0,
    };
}
async function fetchIntroduceInfo({ id }: { url: string, id: string }): Promise<VideoIntroduceInfo> {
    const url = `https://www.iysdq.com/voddetail/${id}.html`;
    const res = await fetch(url, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    // 提取标题（使用精确选择器）
    const title = $('.this-desc-title').text().trim() || '';

    // 提取封面（处理可能的CSS背景图片）
    const coverStyle = $('.this-pic-bj').css('background-image') || '';
    const cover = coverStyle.replace(/^url\("?|"?$|\)$/g, '') || '';

    // 提取导演信息（使用精确索引）
    const directorElement = $('.this-info').eq(0).find('a');
    const director = directorElement.length > 0 ? directorElement.text().trim() : '';

    // 提取演员信息（使用map和精确索引）
    const actors = $('.this-info').eq(1).find('a')
        .map((_: number, el: any) => $(el).text().trim())
        .get()
        .filter(Boolean)
        .join(',') || '';

    // 提取描述信息（移除前缀并清理空白）
    const descriptionElement = $('#height_limit.text');
    const description = descriptionElement.length > 0
        ? descriptionElement.text().replace(/^描述:/, '').trim()
        : '';

    // 提取年份信息（使用正则提取）
    const yearElement = $('.this-desc-info span').eq(1).text();
    const yearMatch = yearElement.match(/(\d{4})/);
    const year = yearMatch ? yearMatch[1] : '';

    // 提取地区信息（使用精确索引）
    const region = $('.this-desc-info span').eq(2).text() || '';

    // 提取分类信息（使用精确选择器）
    const category = $('.this-desc-tags span').first().text() || '';

    // 提取评分信息（使用精确选择器）
    const score = $('.fraction').text() || '';

    // 提取播放地址
    const playUrl = $('.anthology-list-play  li a').attr('href') || '';
    let playId = '';

    // 从URL中提取ID
    const urlMatch = playUrl.match(/\/vodplay\/(\d+)-(\d+)-(\d+)\.html/);
    if (urlMatch) {
        playId = urlMatch[1];
    }

    return {
        id,
        title,
        img: cover?.replace(/'/g, ''),
        introduce: description,
        actor: actors,
        category,
        area: region,
        year,
        score,
        director,
        playUrl
    };
};
async function fetchVideoDetailInfo({ id, source, episodeIndex }: {
    url: string
    id: string,
    source?: number,
    episodeIndex?: number
}): Promise<VideoDetailInfo> {
    const relUrl = `${id}-${(source ? source : 1)}-${(episodeIndex ? episodeIndex : 1)}.html`
    const target = `https://www.iysdq.com/vodplay/${relUrl}`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    const title = $('title').text().split('_')[0];
    const description = $('meta[name="description"]').attr('content') || '';

    // 提取播放源信息
    const playSources: PlaySource[] = [];

    // 解析播放源
    $('.anthology-tab .swiper-wrapper a.vod-playerUrl').each((index: number, element: any) => {
        const sourceName = $(element).text().trim();
        const sourceId = $(element).attr('data-form') || '';

        if (sourceName && sourceId) {
            // 解析对应播放源的剧集
            const episodes: Episode[] = [];
            const episodeList = $(`.anthology-list-play`).eq(index).find('li');

            episodeList.each((epIndex: number, epElement: any) => {
                const episodeTitle = $(epElement).find('span').text().trim();
                const episodeUrl = $(epElement).find('a').attr('href') || '';
                // 从URL中提取ID和集数信息
                const urlMatch = episodeUrl.match(/\/vodplay\/(\d+)-(\d+)-(\d+)\.html/);
                // 验证必要字段
                if (urlMatch && episodeTitle && episodeUrl) {
                    episodes.push({
                        title: episodeTitle,
                        url: episodeUrl,
                        id: urlMatch[1],
                        sourceIndex: parseInt(urlMatch[2], 10),
                        episodeIndex: parseInt(urlMatch[3], 10),
                    });
                }
            });

            // 仅当存在有效剧集时才添加播放源
            if (episodes.length > 0) {
                playSources.push({
                    name: sourceName,
                    id: sourceId,
                    episodes
                });
            }
        }
    });
    // 获取当前播放的视频信息
    const scriptText = html;
    const videoInfo: any = {};

    // 步骤1：匹配变量声明的起始部分
    const startRegex = /var\s+player_aaaa\s*=\s*\{/;
    const startMatch = scriptText.match(startRegex);

    if (!startMatch) {
        console.log("未找到player_aaaa变量声明");
    } else {
        // 步骤2：从第一个{开始截取剩余字符串
        const remainingStr = scriptText.split(startMatch[0])[1];


        // 步骤3：平衡匹配花括号，找到完整的JSON结束位置
        let braceCount = 1; // 已找到1个{
        let endIndex = 0;

        for (let i = 0; i < remainingStr.length; i++) {
            const char = remainingStr[i];
            if (char === '{') {
                braceCount++;
            } else if (char === '}') {
                braceCount--;
                if (braceCount === 0) {
                    endIndex = i; // 找到最后一个}的位置
                    break;
                }
            }
        }

        if (braceCount === 0) {
            // 提取完整的JSON字符串（包含外层{}）
            const jsonStr = '{' + remainingStr.slice(0, endIndex + 1);

            try {
                const playerConfig = JSON.parse(jsonStr);

                console.log("player_aaaa:", playerConfig);

                if (playerConfig.url) {
                    videoInfo.videoUrl = playerConfig.url;
                }
                if (playerConfig.from) {
                    videoInfo.from = playerConfig.from;
                }
                if (playerConfig.id) {
                    videoInfo.playId = playerConfig.id;
                }
                if (playerConfig.sid) {
                    videoInfo.currentEpisode = playerConfig.sid;
                }
                if (playerConfig.nid) {
                    videoInfo.currentSource = playerConfig.nid;
                }
                if (playerConfig.link) {
                    videoInfo.link = playerConfig.link;
                }
            } catch (e) {
                console.error("JSON解析失败：", e, "提取的字符串：", jsonStr);
            }
        } else {
            console.log("未找到完整的JSON结构（花括号不匹配）");
        }
    }




    // 如果没有从player_aaaa中获取到URL，则尝试其他方式
    if (!videoInfo.videoUrl) {
        // 提取视频播放地址
        const urlMatch = scriptText.match(/"url":\s*"([^"]+)"/);
        if (urlMatch) {
            videoInfo.videoUrl = urlMatch[1].replace(/\\\//g, '/').replace(/\\(.)/g, '$1');
        }
    }

    // 从URL中提取ID和集数信息（如果没有从player_aaaa中提取到）
    if (!videoInfo.playId || !videoInfo.currentEpisode || !videoInfo.currentSource) {
        const idMatch = scriptText.match(/.*\/vodplay\/(\d+)-(\d+)-(\d+)\.html/);
        if (idMatch) {
            if (!videoInfo.playId) videoInfo.playId = idMatch[1];
            if (!videoInfo.currentEpisode) videoInfo.currentEpisode = idMatch[2];
            if (!videoInfo.currentSource) videoInfo.currentSource = idMatch[3];
        }
    }

    // 提取播放页面链接（如果没有从player_aaaa中提取到）
    if (!videoInfo.link) {
        const linkMatch = scriptText.match(/"link":\s*"([^"]+)"/);
        if (linkMatch) {
            videoInfo.link = linkMatch[1].replace(/\\\//g, '/').replace(/\\(.)/g, '$1');
        }
    }

    // 提取播放源标识（如果没有从player_aaaa中提取到）
    if (!videoInfo.from) {
        const fromMatch = scriptText.match(/"from":\s*"([^"]+)"/);
        if (fromMatch) {
            videoInfo.from = fromMatch[1];
        }
    }
    const introduce = $('.card-text').text().replace(/^描述:/, '').trim() || ''
    return {
        id,
        title,
        img: '',
        introduce,
        playSources,
        currentVideoInfo: videoInfo,
        detailUrl:`/vodplay/${relUrl}`,
    };

};
module.exports = {
    label: "影视大全",
    platform: "iysdq",
    srcUrl: "https://www.iysdq.com",
    author: "petter.he",
    description: "iysdq",
    enabledSearch: true,
    search,
    fetchIntroduceInfo,
    fetchVideoDetailInfo,
}
